<!--
* @author wn
* @date 2023/10/27 11:05:01
* @description: 新建 与 修改 地址 表单
!-->
<template>
	<view class="content">
		<uni-forms
			:rules="rules"
			ref="formRef"
			:modelValue="form"
			validate-trigger="submit"
		>
			<!-- 表单内容 -->
			<uni-forms-item
				required
				name="receiver"
				class="form-item"
				label="收货人"
				label-width="160rpx"
				label-align="right"
			>
				<input
					class="input"
					placeholder="请填写收货人姓名"
					v-model="receiver"
				/>
			</uni-forms-item>
			<uni-forms-item
				required
				name="contact"
				class="form-item"
				label="手机号码"
				label-width="160rpx"
			>
				<input
					class="input"
					placeholder="请填写收货人手机号码"
					v-model="contact"
				/>
			</uni-forms-item>
			<uni-forms-item
				required
				name="fullLocation"
				class="form-item"
				label="所在地区"
				label-width="160rpx"
			>
				<!-- #ifdef MP-WEIXIN -->
				<picker
					class="picker"
					mode="region"
					:value="fullLocation.split(' ')"
					@change="onRegionChange"
				>
					<view v-if="fullLocation">{{ fullLocation }}</view>
					<view v-else class="placeholder">请选择省/市/区(县)</view>
				</picker>
				<!-- #endif -->
				<!-- picker 仅支持小程序端 uni-data-picker适合做地区联动,数据源 来自云开发，json等
          change事件不改变fullLocation 所以校验规则 重新定义为 countyCode
        -->
				<!-- #ifdef APP-PLUS || H5-->
				<uni-data-picker
					placeholder="请选择地址"
					popup-title="请选择城市"
					collection="opendb-city-china"
					field="code as value, name as text"
					orderby="value asc"
					:step-searh="true"
					self-field="code"
					parent-field="parent_code"
					@change="onCityChange"
					:clear-icon="false"
					v-model="form.countyCode"
				/>
				<!-- #endif -->
			</uni-forms-item>
			<uni-forms-item
				required
				name="address"
				class="form-item"
				label="详细地址"
				label-width="160rpx"
			>
				<input
					class="input"
					placeholder="街道、楼牌号等信息"
					v-model="address"
				/>
			</uni-forms-item>
			<view class="form-item">
				<label class="label">设为默认地址</label>
				<switch
					class="switch"
					color="#27ba9b"
					:checked="isDefault === 1"
					@change="onSwitchChange"
				/>
			</view>
		</uni-forms>
	</view>
	<!-- 提交按钮 -->
	<button class="button" @tap="onSubmit">保存并使用</button>
</template>
<script lang="ts" setup>
import {
	addMemberAddressApi,
	getMemberAddressByIdApi,
	updateMemberAddressByIdApi,
} from '@/api/address'
import { onLoad } from '@dcloudio/uni-app'
import { reactive, ref, toRefs } from 'vue'

/**
 * 通过传递的 id 判断 是 新建 还是 修改
 * navigator 跳转
 * 一级页面: onHide   二级页面:setup onLoad onShow onReady
 * 返回时    二级页面: onUnload 一级页面: onShow 不会触发这之前的 setup-->Load
 * 再次进入  二级页重新加载  setup onLoad onShow onReady
 */
const { id } = defineProps<{ id?: string }>()

/**
 * 有 id 才会调用
 * 拷贝数据到 form 中 做 数据回显
 */
const getAddressById = async () => {
	if (!id) return
	const address = await getMemberAddressByIdApi(id)
	Object.assign(form, address)
}

onLoad(() => {
	getAddressById()
})

// 动态设置标题  默认新建
uni.setNavigationBarTitle({ title: id ? '修改地址' : '新建地址' })

// 表单数据
const form = reactive<AddressParams & { fullLocation: string }>({
	receiver: '', // 收货人
	contact: '', // 联系方式
	fullLocation: '', // 省市区(前端展示)
	provinceCode: '', // 省份编码(后端参数)
	cityCode: '', // 城市编码(后端参数)
	countyCode: '', // 区/县编码(后端参数)
	address: '', // 详细地址
	isDefault: 0, // 默认地址，1为是，0为否
})
const { receiver, contact, fullLocation, address, isDefault } = toRefs(form)

// 收集所在地区
// #ifdef MP-WEIXIN
const onRegionChange: UniHelper.RegionPickerOnChange = e => {
	// 地址名称
	form.fullLocation = e.detail.value.join(' ')
	// 地址编码
	const [provinceCode, cityCode, countyCode] = e.detail.code!
	form.provinceCode = provinceCode
	form.cityCode = cityCode
	form.countyCode = countyCode
}
// #endif

// #ifdef H5 || APP-PLUS
const onCityChange: UniHelper.UniDataPickerOnChange = ev => {
	// 省市区
	const [province, city, county] = ev.detail.value
	// 收集后端所需的 code 数据
	Object.assign(form, {
		provinceCode: province.value,
		cityCode: city.value,
		countyCode: county.value,
	})
}
// #endif

// 收集是否默认收货地址
const onSwitchChange: UniHelper.SwitchOnChange = e => {
	form.isDefault = e.detail.value ? 1 : 0
}

// 表单校验 -- 定义校验规则
const rules: UniHelper.UniFormsRules = {
	receiver: {
		rules: [{ required: true, errorMessage: '请输入收货人姓名' }],
	},
	contact: {
		rules: [
			{ required: true, errorMessage: '请输入联系方式' },
			{ pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' },
		],
	},
	fullLocation: {
		rules: [{ required: true, errorMessage: '请选择所在地区' }],
	},
	address: {
		rules: [{ required: true, errorMessage: '请选择详细地址' }],
	},
}
// 表单校验 -- 表单实例
const formRef = ref<UniHelper.UniFormsInstance>()

// 提交表单 -- 校验
const onSubmit = async () => {
	// 校验通过
	const validate = await formRef.value?.validate?.()?.catch(() => {
		uni.showToast({ icon: 'error', title: '请填写完整信息' })
	})
	if (!validate) return

	// 区分 是 修改 还是 新增
	if (id) {
		await updateMemberAddressByIdApi(id, form) // 修改
	} else {
		await addMemberAddressApi(form) // 新建
	}
	// 成功提示
	uni.showToast({
		icon: 'success',
		title: id ? '修改成功' : '新建成功',
	})
	// 返回上一页
	setTimeout(() => {
		uni.navigateBack()
	}, 400)
}
</script>
<style lang="scss">
.content {
	margin: 20rpx 20rpx 0;
	padding: 0 20rpx;
	border-radius: 10rpx;
	background-color: #fff;

	.uni-forms-item {
		display: flex;
		min-height: 96rpx;
		padding: 25rpx 10rpx 40rpx;
		font-size: 28rpx;
		border-bottom: 1rpx solid #ddd;
		margin-bottom: 0;
		// 调整 uni-forms 样式
		// .uni-forms-item__content {
		// 	display: flex;
		// }

		// .uni-forms-item__error {
		// 	margin-left: 200rpx;
		// }
		.is-required {
			margin-right: 10rpx;
		}
		// .uni-forms-item__label {
		// 	width: 180rpx !important;
		// }
		&:last-child {
			border: none;
		}

		.input {
			flex: 1;
			display: block;
			height: 100%;
		}
		.picker {
			flex: 1;
		}
		.placeholder {
			color: #808080;
		}
	}
	.form-item {
		display: flex;
		align-items: center;
		.label {
			margin: 26rpx 10rpx;
			color: #333;
		}
		.switch {
			margin-left: 280rpx;
			transform: scale(0.8);
		}
	}
}

.button {
	height: 80rpx;
	margin: 30rpx 20rpx;
	color: #fff;
	border-radius: 80rpx;
	font-size: 30rpx;
	background-color: $primary-color;
}
</style>
